using Domain.Entities;
using Domain.Entities.Enums;
using Domain.Mail;
using Domain.Misc;
using Domain.Services;
using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;

namespace UserInterface.Admin
{
    public partial class ReserveUsername : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GroupsListBox.DataSource = GroupService.GetAll();
                GroupsListBox.DataBind();
            }
        }

        protected void ReserveUsernameButton_Click(object sender, EventArgs e)
        {
            string username = UsernameTextBox.Text.Trim();
            string email = EmailTextBox.Text.Trim();
            string password = RandomStringGenerator.Generate(8);
            IList<Group> groups = new List<Group>();

            foreach (ListItem li in GroupsListBox.Items)
            {
                if (li.Selected)
                {
                    Group group = GroupService.GetById(Convert.ToInt16(li.Value));
                    groups.Add(group);
                }
            }

            User newUser = UserService.NewUser(username, email, password, UserStatus.Reserved, groups);

            MailParser mailParser = new MailParser(Server.MapPath("~/Emails/UsernameReserved.xml"));
            mailParser.AddBodyTag("Username", newUser.Username);
            mailParser.AddBodyTag("Password", password);
            mailParser.AddBodyTag("ActivationUrl", "http://" + Request.ServerVariables["HTTP_HOST"] + "/ActivateAccount.aspx?userId=" + newUser.Id + "&activationKey=" + newUser.ActivationKey);

            MailSender mailSender = new MailSender(mailParser);
            mailSender.AddRecipient(email);
            mailSender.Send();
        }
    }
}
